<template>
  <div class="pagestyle">
    <list_controller ref="zujianname" :options="state.options" :noprintDownShow="true">
      <template v-slot:opraCurdBtnlist="row">
        <span>
          <el-button
            class="tableFontSize"
            type="primary"
            link
            size="small"
            @click="lookBtn(row.row.row)"
            >查看
          </el-button>
          <el-button
            class="tableFontSize"
            type="primary"
            link
            size="small"
            @click="editBtn(row.row.row)"
            >编辑
          </el-button>
        </span>
      </template>
      <template v-slot:selectNamelist> 环网列表 </template>
      <template v-slot:opraCurdBtnAll>
        <span
          style="margin-right: 16px"
          :class="state.addModalpoint ? 'listInfoBtn active' : 'listInfoBtn'"
          @click="confingBtn"
        >
          <svg-icon
            :class="state.addModalpoint ? 'active' : ''"
            class-name="search-icon"
            icon-class="qitashezhi"
          />
          配置通道
        </span>
        <!-- <el-button
          class="btn tableFontSize"
          type="primary"
          link
          @click="confingBtn()"
        >
          <el-icon style="margin-right: 2px">
            <svg-icon class-name="search-icon" icon-class="ring" /> </el-icon
          >配置通道
        </el-button> -->
        <oneclickDelivery :yesno="state.yesno"></oneclickDelivery>
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal
        esc-closable
        destroy-on-close
        :lock-view="false"
        :width="660"
        :height="auto"
        v-model="state.addModal"
        resize
        :mask="true"
        showFooter
      >
        <template #title>
          <div class="w100 h100 fsc mask_title">{{ state.modalTitle }}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form
              ref="formRef"
              :model="state.formData"
              :rules="state.rules"
              label-position="top"
            >
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-form-item label="IP地址" prop="ipAddr">
                    <el-input
                      v-model="state.formData.ipAddr"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="端口" prop="ipPort">
                    <el-input
                      v-model="state.formData.ipPort"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="通道号" prop="channelNo">
                    <el-select
                      clearable
                      filterable
                      v-model="state.formData.channelNo"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in state.stationInNumList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="分站编号">
                    <el-input
                      disabled
                      v-model="state.formData.stationCode"
                      placeholder="请输入"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="分站类型">
                    <el-input
                      disabled
                      v-model="state.formData.stationTypeName"
                      placeholder="请输入"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="安装地点">
                    <el-input
                      disabled
                      v-model="state.formData.stationPlaceName"
                      placeholder="请输入"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 详情 -->
    <el-drawer
      v-model="state.drawerShow"
      direction="rtl"
      size="40%"
      close-on-click-modal
      :modal="true"
    >
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="biaotitubiao" /><span
            >环网详情</span
          >
        </h4>
      </template>
      <p class="drawer_sub_title">
        <span class="sub_title_line">基础信息</span>
      </p>
      <div>
        <el-row
          :gutter="20"
          style="
            background: rgba(91, 109, 128, 0.04);
            display: flex;
            align-items: center;
            padding: 20px 0;
          "
        >
          <el-col :span="6">
            <p>IP地址</p>
            <p>{{ state.formData.ipAddr }}</p>
          </el-col>
          <el-col :span="6">
            <p>端口</p>
            <p>{{ state.formData.ipPort }}</p>
          </el-col>
          <el-col :span="6">
            <p>通道号</p>
            <p v-if="state.formData.channelNo != null">
              {{ state.formData.channelNo }}
            </p>
            <p v-else>-</p>
          </el-col>
          <el-col :span="6">
            <p>分站编号</p>
            <p>{{ state.formData.stationCode }}</p>
          </el-col>
          <el-col :span="6">
            <p>分站类型</p>
            <p>{{ state.formData.stationTypeName }}</p>
          </el-col>
          <el-col :span="6">
            <p>安装地点</p>
            <p>{{ state.formData.stationPlaceName }}</p>
          </el-col>
        </el-row>
      </div>
    </el-drawer>
    <!-- 配置通道 -->
    <teleport to="body">
      <vxe-modal
        esc-closable
        destroy-on-close
        :lock-view="false"
        :width="1200"
        v-model="state.addModalpoint"
        resize
        :mask="true"
        showFooter
      >
        <template #title>
          <div class="w100 h100 fsc mask_title">区域测点配置</div>
        </template>
        <template #default>
          <div class="form_box" style="height: 540px">
            <el-form
              ref="formRef2"
              :model="state.formDatapoint"
              :rules="state.rulespoint"
              label-position="top"
            >
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="选择通道" prop="channelNo">
                    <el-select
                      clearable
                      filterable
                      v-model="state.formDatapoint.channelNo"
                      placeholder="请选择"
                      @change="channelNoChange"
                    >
                      <el-option
                        v-for="item in state.stationInNumList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label="待选环网">
                    <vxe-table
                      :loading="loading"
                      height="500"
                      class="w100"
                      :data="state.formDatapoint.unselectedNetworkList"
                      border="inner"
                      @checkbox-change="checkchange1"
                    >
                      <vxe-column type="checkbox" width="42"></vxe-column>
                      <vxe-column title="IP地址:端口">
                        <template #default="{ row }">
                          {{ row.ipAddr }}:{{ row.ipPort }}
                        </template>
                      </vxe-column>
                      <vxe-column
                        field="stationCode"
                        title="分站编号"
                      ></vxe-column>
                      <vxe-column
                        field="stationTypeName"
                        title="分站类型"
                      ></vxe-column>
                      <vxe-column
                        field="stationPlaceName"
                        title="安装地点"
                      ></vxe-column>
                    </vxe-table>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <div class="fdcc h100">
                    <span
                      class="spanBox1 hover"
                      :style="{
                        cursor:
                          state.formDatapoint.channelNo != ''
                            ? 'pointer'
                            : 'not-allowed',
                      }"
                      @click="confirmClick"
                    >
                      <svg-icon
                        class-name="search-icon"
                        icon-class="addblue"
                      />添加
                    </span>
                    <span
                      class="spanBox1 spanBox2 hover"
                      @click="cancelClick"
                      style="margin-top: 10px"
                    >
                      <span>
                        <svg-icon
                          class-name="search-icon"
                          icon-class="delred"
                        />
                        移除</span
                      ></span
                    >
                  </div>
                </el-col>
                <el-col :span="10">
                  <el-form-item label="已选环网">
                    <vxe-table
                      :loading="loading"
                      height="500"
                      class="w100"
                      :data="state.formDatapoint.selectedNetworkList"
                      :checkbox-config="checkboxConfig"
                      @checkbox-change="selectChangeEvent"
                      border="inner"
                    >
                      <vxe-column type="checkbox" width="42"></vxe-column>
                      <vxe-column title="IP地址:端口">
                        <template #default="{ row }">
                          {{ row.ipAddr }}:{{ row.ipPort }}
                        </template>
                      </vxe-column>
                      <vxe-column
                        field="stationCode"
                        title="分站编号"
                      ></vxe-column>
                      <vxe-column
                        field="stationTypeName"
                        title="分站类型"
                      ></vxe-column>
                      <vxe-column
                        field="stationPlaceName"
                        title="安装地点"
                      ></vxe-column>
                    </vxe-table>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
        <template #footer>
          <el-button @click="cancelpoint">取消</el-button>
            <el-button type="primary" @click="submitFormponit">
              确定
            </el-button>
        </template>
      </vxe-modal>
    </teleport>
  </div>
</template>
<script setup>
import list_controller from "@/components/commonCom/list_controller";
import { computed, reactive, onBeforeUnmount } from "vue";
import { table_headers } from "@/components/commonCom/table_headers";
import oneclickDelivery from "@/components/commonCom/oneclickDelivery";
import axios from "@/utils/request";
import usePagesStore from "@/store/modules/pages";
import {
  searchchannelNoList,
} from "@/api/config";
const { proxy } = getCurrentInstance();
const store = usePagesStore();
const router = useRouter();
/** 校验输入内容是否为正整数 */
const validateip = (rule, value, callback) => {
  let reg =
    /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.((1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/;
  if (!reg.test(value)) return callback(new Error("请输入正确的IP"));
  callback();
};
const validatePass = (rule, value, callback) => {
  let reg = new RegExp(
    /^([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/
  );
  if (!reg.test(value)) return callback(new Error("请输入正确的端口"));
  callback();
};
let previewHttps = import.meta.env.VITE_APP_HTTP;
components: {
  list_controller, oneclickDelivery;
}
const upload = ref(null);
let state = reactive({
  yesno: false,
  options: {
    tableheads: computed(() => table_headers.netWork),
    queryList: {
      dropdownUrl: "",
      querys: [
        {
          field: "condition",
          title: "搜索",
          type: "input",
          tip: "请输入IP、安装地址",
          binddata: "",
        },
        {
          field: "channelNo",
          title: "通道号",
          type: "select",
          binddata: "",
          options: [],
        },
      ],
      queryMap: new Map([
        ["sensorTypeId", "safety_pointType"],
        ["deviceTypeId", "safety_deviceType"],
        ["alarmTypeId", "alarmType"],
      ]),
    },
    dataUrl: "/station/netList",
    delUrl: "/substation/type/deleteStation",
    addUrl: "/substation/type/addStation",
    descUrl: "/station/netDetail/",
    editUrl: "/station/modifyNet",
  },
  // 表单
  addModal: false,
  modalTitle: "环网编辑",
  drawerShow: false,
  formRef: null,
  formData: {},
  rules: {
    ipAddr: [
      {
        required: true,
        message: "请输入IP地址",
        trigger: "blur",
      },
      {
        validator: validateip,
        trigger: "blur",
      },
    ],
    ipPort: [
      {
        required: true,
        message: "请输入端口",
        trigger: "change",
      },
      {
        validator: validatePass,
        trigger: "blur",
      },
    ],
    channelNo: [
      {
        required: true,
        message: "请选择通道号",
        trigger: "change",
      },
    ],
  },
  editId: undefined,
  stationInNumList: [],
  addModalpoint: false,
  formDatapoint: {},
  rulespoint: {
    channelNo: [
      {
        required: true,
        message: "请选择通道号",
        trigger: "change",
      },
    ],
  },
  confirmList: [],
  areaPointList1: [],
  areaPointList: [],
});
// 查看按钮
function lookBtn(row) {
  state.drawerShow = true;
  axios.post(state.options.descUrl + row.id).then((res) => {
    if (res.code == 200) {
      state.formData = res.data;
    }
  });
}

// 通道配置
function confingBtn() {
  state.addModalpoint = true;
  state.formDatapoint.channelNo = undefined;
  getconifgList();
}
// 编辑按钮
function editBtn(row) {
  state.modalTitle = "环网编辑";
  state.addModal = true;
  axios.post(state.options.descUrl + row.id).then((res) => {
    if (res.code == 200) {
      state.formData = res.data;
      state.formData.ipPort = res.data.ipPort;
      state.editId = res.data.id;
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      state.formData.id = state.editId;
      axios.post(state.options.editUrl, state.formData).then((res) => {
        if (res.code == 200) {
          proxy.$refs["zujianname"].getData();
          state.addModal = false;
          proxy.$modal.msgSuccess(res.msg);
        }
      });
    }
  });
}

function cancel() {
  state.addModal = false;
}

function getsubstationmodelList() {
  searchchannelNoList().then((res) => {
    state.stationInNumList = res.data;
    state.options.queryList.querys[1].options = res.data.map((item) => {
      return {
        value: item.id,
        label: item.name,
      };
    });
  });
}
getsubstationmodelList();
// 表格禁用状态
const checkboxConfig = reactive({
  visibleMethod({ row }) {
    return !row.selected;
  },
});

function getconifgList(val) {
  axios
    .post("station/containNetDetail", {
      channelNo: val,
    })
    .then((res) => {
      state.formDatapoint.unselectedNetworkList =
        res.data.unselectedNetworkList;
      state.formDatapoint.selectedNetworkList = res.data.selectedNetworkList;
      if (
        res.data.selectedNetworkList != null &&
        res.data.selectedNetworkList.length > 0
      ) {
        state.formDatapoint.selectedNetworkList =
          res.data.selectedNetworkList.map((item) => {
            item.selected = false;
            return item;
          });
      } else if (res.data.selectedNetworkList == null) {
        res.data.selectedNetworkList = [];
        state.formDatapoint.selectedNetworkList = res.data.selectedNetworkList;
      }
    });
}

function channelNoChange(val) {
  getconifgList(val);
}

function checkchange1(e) {
  let arr = e.records;
  state.confirmList = arr;
}

function selectChangeEvent(e) {
  state.areaPointList1 = e.records;
  state.areaPointList = e.records.map((item) => {
    return {
      id: item.id,
    };
  });
}

function confirmClick() {
  if (state.formDatapoint.selectedNetworkList == null) {
    state.formDatapoint.selectedNetworkList = [];
  }
  state.formDatapoint.unselectedNetworkList =
    state.formDatapoint.unselectedNetworkList.filter(
      (el) => !state.confirmList.includes(el)
    );
  state.formDatapoint.selectedNetworkList =
    state.formDatapoint.selectedNetworkList.concat(state.confirmList);
}

function cancelClick() {
  state.formDatapoint.selectedNetworkList =
    state.formDatapoint.selectedNetworkList.filter(
      (el) => !state.areaPointList1.includes(el)
    );
  state.formDatapoint.unselectedNetworkList =
    state.formDatapoint.unselectedNetworkList.concat(state.areaPointList1);
}

function submitFormponit() {
  proxy.$refs["formRef2"].validate((valid) => {
    if (valid) {
      axios
        .post("/station/modifyNetDetail", {
          channelNo: state.formDatapoint.channelNo,
          stationBasicDtoList: state.areaPointList,
        })
        .then((res) => {
          proxy.$modal.msgSuccess(res.msg);
          state.addModalpoint = false;
          proxy.$refs.zujianname.getData()
        });
    }
  });
}

function cancelpoint() {
  state.addModalpoint = false;
}
onBeforeUnmount(() => {
  console.log("卸载前");
  state.yesno = !state.yesno;
});
</script>
<style lang="scss" scoped>
.spanBox1 {
  display: inline-block;
  background-image: url("@/assets/images/configbg.png");
  width: 80px;
  height: 35px;
  line-height: 35px;
  text-align: center;

  &.spanBox2 {
    background-image: url("@/assets/images/configbg2.png");
  }
}
:deep(.vxe-modal--content) {
  overflow: hidden !important;
}
</style>
